
# encoding:utf-8
# api method
from  dotenv import load_dotenv,find_dotenv
import os
import requests
import base64

load_dotenv(find_dotenv())
api_key = os.getenv('API_KEY')
security_key=os.getenv('SECRET_KEY')

host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+ api_key+ '&client_secret=' + security_key
response = requests.get(host)
if response:
    res = response.json()

access_token = res['access_token']

'''
通用文字识别
'''
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
# 二进制方式打开图片文件
f = open('./cover.jpg', 'rb')
img = base64.b64encode(f.read())

params = {"image":img}
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
if response:
    res = response.json()

words_result = res['words_result']
for item in words_result:
    print(item['words'])
